<template>
  <el-row class="mb-5">
    <el-alert
      v-if="expiredCertificateTypes.length > 0"
      :title="
        expiredCertificateTypes.length ? expiredTitle[0] : expiredTitle[1]
      "
      type="error"
    />
    <el-alert
      v-if="expiringCertificateTypes.length > 0"
      :title="
        expiringCertificateTypes.length ? expiringTitle[0] : expiringTitle[1]
      "
      type="warning"
      class="mt-2"
    />
  </el-row>
  <el-row justify="end" class="mb-2">
    <el-button text :icon="CirclePlus" @click="initModalModalGenerateCsr">
      {{ $t('pageCertificates.generateCsr') }}
    </el-button>
    <el-button
      :type="certificatesForUpload.length === 0 ? '' : 'primary'"
      :icon="CirclePlus"
      @click="initModalUploadCertificate(null)"
      :disabled="certificatesForUpload.length === 0"
    >
      {{ $t('pageCertificates.addNewCertificate') }}
    </el-button>
  </el-row>

  <el-table
    ref="tableRef"
    row-key="groupName"
    style="width: 100%"
    :data="certificates"
    :empty-text="$t('global.table.emptyMessage')"
    border
  >
    <el-table-column
      prop="certificate"
      :label="$t('pageCertificates.table.certificate')"
    />
    <el-table-column
      prop="issuedBy"
      :label="$t('pageCertificates.table.issuedBy')"
    />
    <el-table-column
      prop="issuedTo"
      :label="$t('pageCertificates.table.issuedTo')"
    />
    <el-table-column
      prop="validFrom"
      :label="$t('pageCertificates.table.validFrom')"
    >
      <template #default="scope">
        {{ globalStore.formatDate(scope.row.validFrom) }}
      </template>
    </el-table-column>
    <el-table-column
      prop="validUntil"
      :label="$t('pageCertificates.table.validUntil')"
    >
      <template #default="scope">
        <el-tag
          v-if="(getDaysUntilExpired(scope.row.validUntil) as number) < 31"
          :type="getTagStatus(scope.row.validUntil)"
          disable-transitions
          >{{ scope.row.severity }}</el-tag
        >
        {{ globalStore.formatDate(scope.row.validUntil) }}
      </template>
    </el-table-column>
    <el-table-column label="Operations">
      <template #default="scope">
        <el-tooltip
          class="box-item"
          effect="dark"
          :content="$t('pageCertificates.replaceCertificate')"
          placement="top-start"
        >
          <el-button
            type="primary"
            :icon="RefreshRight"
            @click="handleReplaceCertificate(scope.row)"
          />
        </el-tooltip>
        <el-tooltip
          class="box-item"
          effect="dark"
          :content="$t('pageCertificates.deleteCertificate')"
          placement="top-start"
        >
          <el-button
            :type="scope.row.type !== 'TrustStore Certificate' ? '' : 'danger'"
            class="bg-orange-600"
            :icon="Delete"
            @click="handleDelete(scope.row)"
            :disabled="
              scope.row.type !== 'TrustStore Certificate' ? true : false
            "
          />
        </el-tooltip>
      </template>
    </el-table-column>
  </el-table>

  <modal-upload-certificate
    :certificate="modalCertificate"
    ref="modalUploadCertificateRef"
    @ok="onModalOk"
  />
  <modal-generate-csr ref="modalModalGenerateCsrRef" />
</template>

<script setup lang="ts">
import { RefreshRight, Delete, CirclePlus } from '@element-plus/icons-vue';
import ModalUploadCertificate from './ModalUploadCertificate.vue';
import ModalGenerateCsr from './ModalGenerateCsr.vue';
import { useI18n } from 'vue-i18n';
import { useCertificatesStore } from '@/store/UserSecurity/Certificates/CertificatesStore';
import { useGlobalStore } from '@/store/global';

const CertificatesStore = useCertificatesStore();
const globalStore = useGlobalStore();

await globalStore.getBmcTime();
await CertificatesStore.getCertificates();

const i18n = useI18n();

const expiredTitle = computed(() => [
  i18n.t('pageCertificates.alert.certificatesExpiringMessage'),
  i18n.t('pageCertificates.alert.certificateExpiringMessage', {
    certificate: expiringCertificateTypes.value[0],
  }),
]);

const expiringTitle = computed(() => [
  i18n.t('pageCertificates.alert.certificatesExpiringMessage'),
  i18n.t('pageCertificates.alert.certificateExpiringMessage', {
    certificate: expiringCertificateTypes.value[0],
  }),
]);

const modalCertificate = ref();

const certificates = computed(() => CertificatesStore.allCertificates);

const certificatesForUpload = computed(
  () => CertificatesStore.availableUploadTypes,
);
const bmcTime = computed(() => globalStore.bmcTime);

const expiredCertificateTypes = computed(() => {
  return certificates.value.reduce(
    (acc: any[], val: { validUntil: any; certificate: any }) => {
      const daysUntilExpired = getDaysUntilExpired(val.validUntil) as number;
      if (daysUntilExpired < 1) {
        acc.push(val.certificate);
      }
      return acc;
    },
    [],
  );
});
const expiringCertificateTypes = computed(() => {
  return certificates.value.reduce(
    (acc: any[], val: { validUntil: any; certificate: any }) => {
      const daysUntilExpired = getDaysUntilExpired(val.validUntil) as number;
      if (daysUntilExpired < 31 && daysUntilExpired > 0) {
        acc.push(val.certificate);
      }
      return acc;
    },
    [],
  );
});

const modalUploadCertificateRef = ref();
const initModalUploadCertificate = (certificate = null) => {
  modalCertificate.value = certificate;
  modalUploadCertificateRef.value.dialogVisible = true;
};
const handleReplaceCertificate = (row: any) => {
  initModalUploadCertificate(row);
};

const addNewCertificate = (file: any, type: any) => {
  CertificatesStore.addNewCertificate({ file, type })
    .then((message: string) =>
      ElNotification({
        title: 'Success',
        message,
        type: 'success',
      }),
    )
    .catch(({ message }: { message: string }) =>
      ElNotification({
        title: 'Error',
        message,
        type: 'error',
      }),
    );
};
const replaceCertificate = (file: Blob, type: any, location: any) => {
  const reader = new FileReader();
  reader.readAsBinaryString(file);
  reader.onloadend = (event) => {
    const certificateString = event.target!.result;
    CertificatesStore.replaceCertificate({
      certificateString,
      type,
      location,
    })
      .then((message: string) =>
        ElNotification({
          title: 'Success',
          message,
          type: 'success',
        }),
      )
      .catch(({ message }: { message: string }) =>
        ElNotification({
          title: 'Error',
          message,
          type: 'error',
        }),
      );
  };
};

const onModalOk = ({
  addNew,
  file,
  type,
  location,
}: {
  addNew: any;
  file: any;
  type: any;
  location: any;
}) => {
  if (addNew) {
    // Upload a new certificate
    addNewCertificate(file, type);
  } else {
    // Replace an existing certificate
    replaceCertificate(file, type, location);
  }
};
const handleDelete = (row: any) => {
  let { issuedBy, certificate } = row;
  ElMessageBox.confirm(
    i18n.t('pageCertificates.modal.deleteConfirmMessage', {
      issuedBy,
      certificate,
    }),
    i18n.t('pageCertificates.deleteCertificate'),
    {
      confirmButtonText: i18n.t('global.action.delete'),
      cancelButtonText: i18n.t('global.action.cancel'),
      type: 'warning',
    },
  )
    .then(() => {
      deleteCertificate(row);
    })
    .catch(() => {});
};

const deleteCertificate = ({
  type,
  location,
}: {
  type: any;
  location: any;
}) => {
  CertificatesStore.deleteCertificate({
    type,
    location,
  })
    .then((message: string) =>
      ElNotification({
        title: 'Success',
        message,
        type: 'success',
      }),
    )
    .catch(({ message }: { message: string }) =>
      ElNotification({
        title: 'Error',
        message,
        type: 'error',
      }),
    );
};

const modalModalGenerateCsrRef = ref();
const initModalModalGenerateCsr = () => {
  modalModalGenerateCsrRef.value.dialogVisible = true;
};

const getDaysUntilExpired = (date: { getTime: () => any }) => {
  if (bmcTime.value) {
    const validUntilMs = date.getTime();
    const currentBmcTimeMs = bmcTime.value.getTime();
    const oneDayInMs = 24 * 60 * 60 * 1000;
    return Math.round((validUntilMs - currentBmcTimeMs) / oneDayInMs);
  }
  return new Date();
};
const getTagStatus = (date: { getTime: () => any }) => {
  const daysUntilExpired = getDaysUntilExpired(date) as number;
  if (daysUntilExpired < 1) {
    return 'danger';
  } else if (daysUntilExpired < 31) {
    return 'warning';
  }
};
</script>
